// API配置
const API_BASE_URL = 'http://localhost:8080';

// API请求函数
async function apiRequest(endpoint, options = {}) {
    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`, {
            headers: {
                'Content-Type': 'application/json',
            },
            ...options,
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        if (error.message === 'Failed to fetch') {
            throw new Error('无法连接网络，请确保后端服务已启动');
        }
        throw error;
    }
}

// 导出API函数
export const api = {
    // 用户登录
    login: async (username, password) => {
        return await apiRequest('/api/auth/login', {
            method: 'POST',
            body: JSON.stringify({ username, password }),
        });
    },
    
    // 用户注册
    register: async (username, password) => {
        return await apiRequest('/api/auth/register', {
            method: 'POST',
            body: JSON.stringify({ username, password }),
        });
    },
};